package com.fileupload.fileupload.service.impl;

import com.fileupload.fileupload.config.MinioConfig;
import com.fileupload.fileupload.dao.ExportExcelDateDao;
import com.fileupload.fileupload.handler.DownExcelDateResultHandler;
import com.fileupload.fileupload.handler.MyWebSocketHandler;
import com.fileupload.fileupload.service.ExportExcelDateService;
import com.fileupload.fileupload.utils.MinioFileUtils;
import io.minio.MinioClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.Executor;
import java.util.concurrent.Semaphore;


@Slf4j
@Service
public class ExportExcelDateServiceImpl implements ExportExcelDateService {

    @Autowired
    private ExportExcelDateDao exportExcelDateDao;
    @Autowired
    private MinioConfig minioConfig;
    @Autowired
    private MinioClient minioClient;
    @Autowired
    private MyWebSocketHandler myWebSocketHandler;
    @Resource(name = "exportExcelTaskExecutor")
    private Executor exportExcelTaskExecutor;
    @Resource(name = "exportExcelSemaphore")
    private Semaphore exportExcelSemaphore;
    /**
     * 生成excel文件
     */
    @Override
    public void selectStream() {
        // 尝试获取信号量,否允许执行
        if (exportExcelSemaphore.tryAcquire()){
            // 获取到信号量，开启一个线程，执行查询，将查询的结果写入excel文件
            exportExcelTaskExecutor.execute(() -> {
                DownExcelDateResultHandler resultHandler = new DownExcelDateResultHandler();
                // 执行查询，将查询的结构写入excel文件中
                exportExcelDateDao.selectStream(resultHandler);
                // 结束写入excel文件
                resultHandler.end();
                String filePath = resultHandler.getExeclPath();
                log.info("文件路径：" + filePath);
                // 将本地缓存的execl文件，上传到minio中
                try {
                    String uploadFileMinio = MinioFileUtils.uploadFileMinio(minioClient, minioConfig.getBucketName(), minioConfig.getTempBucket(), filePath);
                    String fileUrl = minioConfig.getEndpoint() + "/" + uploadFileMinio;
                    log.info("文件上传成功，文件路径：" + fileUrl);
                    // 返回文件下载地
                    myWebSocketHandler.sendMessageToClient(fileUrl);
                } catch (Exception e) {
                    log.info("文件上传失败");
                    throw new RuntimeException(e);
                }
                // 释放信号量
                exportExcelSemaphore.release();
            });
        }
        else {
            // todo 获取信号量失败,启用重试机制
            log.info("获取信号量失败");
        }
    }
}
